package com.xnck.demo.flowabledesigner.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.xnck.demo.flowabledesigner.helper.PropertiesConfigurer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
public class DataSourceConfig {

    @Primary
    @Bean(name = "dataSource")
    @ConditionalOnBean(PropertiesConfigurer.class)
    public DataSource getDataSource() throws Exception {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(PropertiesConfigurer.getProperty("db.driver"));
        dataSource.setUrl(PropertiesConfigurer.getProperty("db.url"));
        dataSource.setUsername(PropertiesConfigurer.getProperty("db.user"));
        dataSource.setPassword(PropertiesConfigurer.getProperty("db.password"));
        dataSource.setInitialSize(1);
        dataSource.setMinIdle(1);
        dataSource.setMaxActive(20);
        dataSource.setFilters("stat");
        return dataSource;
    }

    @Primary
    @Bean(name = "transactionManager")
    public DataSourceTransactionManager getDataSourceTransactionManager(@Qualifier("dataSource")DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }
}
